package com.six.service;

import com.six.domain.dto.CreateStoreDto;
import com.six.domain.entity.Store;
import com.six.domain.entity.User;
import com.six.enums.RoleEnum;
import com.six.mapper.StoreMapper;
import com.six.mapper.UserMapper;
import com.six.util.RandomPasswordUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class StoreService {

    private final StoreMapper storeMapper;
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Transactional
    public Map<String, String> createStoreWithManager(CreateStoreDto dto) {
        // 1️⃣ 先创建门店（不设置 managerId）
        Store store = new Store();
        store.setStoreName(dto.getStoreName());
        store.setStoreCode(dto.getStoreCode());
        store.setAddress(dto.getAddress());
        store.setPhone(dto.getPhone());
        // managerId 先不填，后面再 update
        storeMapper.insertStore(store);   // 这一步完成后 store.getId() 就有值了

        // 2️⃣ 再创建店长账号，并把 storeId 回写
        String managerUsername = dto.getStoreCode() + "manager";
        String rawPassword   = RandomPasswordUtil.generate(8);
        User manager = new User();
        manager.setUsername(managerUsername);
        manager.setPasswordHash(passwordEncoder.encode(rawPassword));
        manager.setRoleId(RoleEnum.MANAGER.getId());
        manager.setIsActive(true);
        manager.setStoreId(store.getId());   // ✅ 现在 store 已存在
        userMapper.insertUser(manager);

        // 3️⃣ 把店长 id 回填到门店
        store.setManagerId(manager.getId());
        storeMapper.updateById(store);   // 需要 XML/注解里写 updateById

        return Map.of("username", managerUsername, "password", rawPassword);
    }
    public List<Store> listAllStores() {
        return storeMapper.selectAllStores();
    }

    public Store getStore(Long id) {
        return storeMapper.selectStoreById(id);
    }


}